import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import { queryContractList, offlineContrac } from './service';

import { TableListDate } from './data.d';

export interface StateType {
  data: TableListDate;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & {
    select: <T>(func: (state: StateType) => T) => T;
  }
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    offline: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'parnterFranchiseeContractList',

  state: {
    data: {
      list: [],
      count: 0,
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryContractList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },
    * offline({ payload }, { call, put }) {
      const { id, type, ...query } = payload;
      const response = yield call(offlineContrac, { id, type });
      const data = fetchValidation(response);

      if (data) {
        message.success('终止成功');
        yield put({
          type: 'fetch',
          payload: query,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};

export default Model;
